//
//  ListViewController.swift
//  EnglishDictionary
//
//  Created by QFX on 2024/2/23.
//

import UIKit
import PopOverMenu

class ListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UIAdaptivePresentationControllerDelegate {

    @IBOutlet weak var openEyeLabel: UILabel!
    @IBOutlet weak var openEyeImageView: UIImageView!
    @IBOutlet weak var footView: UIView!
    var words:[Word]?
    var sentences:[Sentence]?
    var fold:Fold?
    var categoryTitle:String?
    var navTitle:String?
    
    /// 每个 section 的标题
    var wSectionTitleArray = [String]()
    var wIndexedCollation = UILocalizedIndexedCollation.current()
    var wDataArray = [[Word]]()
    
    @IBOutlet weak var listenLabel: UILabel!
    var sSectionTitleArray = [String]()
    var sIndexedCollation = UILocalizedIndexedCollation.current()
    var sDataArray = [[Sentence]]()
    
    var type:Int = 0;//0:单词 1：句子
    var isPinyingPai:Bool = false
    var popOverViewController: PopOverViewController?
    var isOpenEyes:Bool = true
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SpeechSynthesizer.Shared.stopSpeak()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = .white
        let scrollEdgeAppearance = UINavigationBarAppearance()
        scrollEdgeAppearance.configureWithOpaqueBackground()
        self.navigationController?.navigationBar.scrollEdgeAppearance = scrollEdgeAppearance
        self.navigationController?.navigationBar.standardAppearance = scrollEdgeAppearance
        self.navigationController?.view.backgroundColor = UIColor.white
        self.navigationController?.navigationBar.barTintColor = .black
        self.navigationItem.title = self.navTitle
        
        self.tableView.dataSource = self
        self.tableView.delegate = self
        
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0.0
        } else {
            // Fallback on earlier versions
        }
        self.tableView.tableHeaderView = UIView()
        self.tableView.tableFooterView = UIView()
        self.tableView.estimatedSectionFooterHeight = 0
        self.tableView.estimatedSectionHeaderHeight = 0
        self.tableView.register(UINib(nibName: "ListCell", bundle: nil), forCellReuseIdentifier: "ListCell")
 
        let barButtonItem = UIBarButtonItem(title: "排序", style: .plain, target: self, action: #selector(self.openMenu(sender:)))
        self.navigationItem.rightBarButtonItem = barButtonItem

        self.footView.layer.cornerRadius = 40
        self.footView.clipsToBounds = true
        
        kNOTIFY_ADD(observer: self, selector: #selector(reloadData), name: "cpSuccess", object: nil)
        getData()
    }
    
    @objc func reloadData() {
        getData()
    }
    
    func getData(){
        if let fold = navTitle{
            if (self.categoryTitle == "Sentences"){
                self.type = 1
                self.listenLabel.text = "听句子"
                self.sentences = Sentence.getSentence(fold: fold)
//                self.sentences = self.sentences?.sorted(by: { w1, w2 in
//                    return w1.sentence! < w2.sentence!
//                })
                let collation = UILocalizedIndexedCollation.current()
                let (countrArr, titlesArr) = collation.partitionObjects(array: self.sentences!,collationStringSelector: #selector(getter: Sentence.sentence))
                sDataArray = countrArr as! [[Sentence]]
                sSectionTitleArray = titlesArr
                self.tableView.reloadData()
            }else{
                self.type = 0
                self.listenLabel.text = "听单词"
                self.words = Word.getWords(fold: fold)
//                self.words = self.words?.sorted(by: { w1, w2 in
//                    return w1.word! < w2.word!
//                })
                let collation = UILocalizedIndexedCollation.current()
                let (countrArr, titlesArr) = collation.partitionObjects(array: self.words!,collationStringSelector: #selector(getter: Word.word))
                wDataArray = countrArr as! [[Word]]
                wSectionTitleArray = titlesArr
                self.tableView.reloadData()
            }
        }
    }
    
 
    @objc func openMenu(sender: UIBarButtonItem) {
        self.popOverViewController = PopOverViewController.instantiate()

        let titles = ["默认排序", "字母排序"]
 
        self.popOverViewController?.setArrayForBarButtonItem(delegate: self, barButtonItem: sender, titles: titles, descriptions: [], separatorStyle: .singleLine,width: 100) { (selectRow) in
            self.isPinyingPai = selectRow == 1
            self.tableView.reloadData()
            print(selectRow)
         }

        if let popOverViewController = self.popOverViewController {
            present(popOverViewController, animated: true, completion: nil)
        }
    }
 
    @IBAction func listen(_ sender: Any) {
        let st = UIStoryboard.init(name: "Main", bundle: nil)
        let vc = st.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        vc.navTitle = self.navTitle
        vc.isAutoScroll = true
        vc.isSort = self.isPinyingPai
        vc.categoryTitle = self.categoryTitle
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func card(_ sender: Any) {
         let st = UIStoryboard.init(name: "Main", bundle: nil)
        let vc = st.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        vc.navTitle = self.navTitle
         vc.isAutoScroll = true
        vc.isSort = self.isPinyingPai
        vc.categoryTitle = self.categoryTitle
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if self.isPinyingPai{
            return  self.type == 0 ? wSectionTitleArray[section] : sSectionTitleArray[section]
        }
        return nil
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if self.isPinyingPai{
            return  self.type == 0 ? wSectionTitleArray : sSectionTitleArray
        }
        return nil
    }
       
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.isPinyingPai{
            return 44
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.isPinyingPai{
            return  self.type == 0 ? wSectionTitleArray.count : sSectionTitleArray.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.isPinyingPai{
            return self.type == 0 ? wDataArray[section].count : sDataArray[section].count
        }
        return  self.type == 0 ? self.words?.count ?? 0 : self.sentences?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "ListCell",for: indexPath) as? ListCell
        if cell == nil {
            cell = ListCell.init(style: .default, reuseIdentifier: ListCell.self.description())
        }
        let row = indexPath.row
        let section = indexPath.section
        
        if self.isPinyingPai{
            if self.type == 0 {
                let word = self.wDataArray[section][indexPath.row]
                cell?.titleLabel.text = word.word
                cell?.subTitleLabel.text = self.isOpenEyes ? word.st : ""
                 cell?.subTitleLabel.backgroundColor = self.isOpenEyes ? UIColor.clear : UIColor.lightGray
                cell?.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            }else{
                let sentence = self.sDataArray[section][indexPath.row]
                cell?.titleLabel.text = sentence.sentence
                cell?.subTitleLabel.text = self.isOpenEyes ? sentence.st : ""
                 cell?.subTitleLabel.backgroundColor = self.isOpenEyes ? UIColor.clear : UIColor.lightGray
                cell?.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            }
        }else{
            if self.type == 0 {
                let word = self.words?[indexPath.row]
                cell?.titleLabel.text = word?.word
                cell?.subTitleLabel.text = self.isOpenEyes ? word?.st : ""
                cell?.subTitleLabel.backgroundColor = self.isOpenEyes ? UIColor.clear : UIColor.lightGray
                cell?.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            }else{
                let sentence = self.sentences?[indexPath.row]
                cell?.titleLabel.text = sentence?.sentence
                cell?.subTitleLabel.text = self.isOpenEyes ? sentence?.st : ""
                 cell?.subTitleLabel.backgroundColor = self.isOpenEyes ? UIColor.clear : UIColor.lightGray
                cell?.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            }
        }
        
        cell?.selectionStyle  = .none

        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let section = indexPath.section
        if self.isPinyingPai{
            if self.type == 0 {
                let word = self.wDataArray[section][row]
                let st = UIStoryboard.init(name: "Main", bundle: nil)
                let vc = st.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
                vc.navTitle = self.navTitle
                vc.word = word
                vc.isSort = true
                vc.categoryTitle = self.categoryTitle
                self.navigationController?.pushViewController(vc, animated: true)
            }else if self.type == 1{
                let sentence = self.sDataArray[section][row]
                let st = UIStoryboard.init(name: "Main", bundle: nil)
                let vc = st.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
                vc.navTitle = self.navTitle
                vc.sentence = sentence
                vc.isSort = true
                vc.categoryTitle = self.categoryTitle
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }else{
            if self.type == 0 {
                let word = self.words?[row]
                let st = UIStoryboard.init(name: "Main", bundle: nil)
                let vc = st.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
                vc.navTitle = self.navTitle
                vc.word = word
                vc.isSort = false
                vc.categoryTitle = self.categoryTitle
                self.navigationController?.pushViewController(vc, animated: true)
            }else if self.type == 1{
                let sentence = self.sentences?[row]
                let st = UIStoryboard.init(name: "Main", bundle: nil)
                let vc = st.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
                vc.navTitle = self.navTitle
                vc.sentence = sentence
                vc.isSort = false
                vc.categoryTitle = self.categoryTitle
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }

    }
    
    @objc func play(sender:UIButton){
        if let cell = sender.superview?.superview as? ListCell{
            if let indexPath = self.tableView.indexPath(for: cell){
                let row = indexPath.row
                let section = indexPath.section
                if self.isPinyingPai{
                    if self.type == 0 {
                        let word = self.wDataArray[section][row]
                        if let wd =  word.word{
                            SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
                               
                            }
                        }
                    }else if self.type == 1{
                        let sentence = self.sDataArray[section][row]
                        if let sentence =  sentence.sentence{
//                            SpeechSynthesizer.Shared.speak(sentence,language:"en-US") { wd in
//
//                            }
                        }
                    }
                }else{
                    if self.type == 0 {
                        let word = self.words?[row]
                        if let wd =  word?.word{
                            SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
                               
                            }
                        }
                    }else if self.type == 1{
                        let sentence = self.sentences?[row]
                        if let sentence =  sentence?.sentence{
//                            SpeechSynthesizer.Shared.speak(sentence,language:"en-US") { wd in
//
//                            }
                        }
                    }
                }
            }
        }
    }
    
    @IBAction func openEyes(_ sender: Any) {
        self.isOpenEyes = !self.isOpenEyes
        self.openEyeLabel.text = self.isOpenEyes ? "隐藏释义" : "显示释义"
        self.openEyeImageView.image = self.isOpenEyes ? UIImage(named: "close_eyes") : UIImage(named: "open_eyes")
        self.tableView.reloadData()
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { context in
            self.popOverViewController?.dismiss(animated: true)
        })
    }

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.none
    }

    func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.none
    }

    // Override to support conditional editing of the table view.
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
 
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
 
    // Override to support editing the table view.
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            let row = indexPath.row
            let section = indexPath.section
            if self.isPinyingPai{
                if self.type == 0 {
                    let word = self.wDataArray[section][row]
                    try?word.delete()
                }else if self.type == 1{
                    let sentence = self.sDataArray[section][row]
                    try?sentence.delete()
                }
            }else{
                if self.type == 0 {
                    let word = self.words?[row]
                    try?word?.delete()
                }else if self.type == 1{
                    let sentence = self.sentences?[row]
                    try?sentence?.delete()
                }
            }
 
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                self.getData()
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                TRHUD.showSuccess("删除成功")
            }
        }
    }
}


extension UILocalizedIndexedCollation{
    
    func partitionObjects(array:[AnyObject], collationStringSelector:Selector) -> ([AnyObject], [String]) {
        var unsortedSections = [[AnyObject]]()
        
        //1. Create a array to hold the data for each section
        for _ in self.sectionTitles {
            unsortedSections.append([]) //appending an empty array
        }
        
        //2. Put each objects into a section
        for item in array {
            let index:Int = self.section(for: item, collationStringSelector:collationStringSelector)
            unsortedSections[index].append(item)
        }
        //3. sorting the array of each sections
        var sectionTitles = [String]()
        var sections = [AnyObject]()
        for index in 0 ..< unsortedSections.count { if unsortedSections[index].count > 0 {
            sectionTitles.append(self.sectionTitles[index])
            sections.append(self.sortedArray(from: unsortedSections[index], collationStringSelector: collationStringSelector) as AnyObject)
            }
        }
        return (sections, sectionTitles)
    }
}
